package com.xnj.testweb.admin.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class MultiThreadExport {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 指定文件保存路径
        String fileName = "D:\\downloadAll\\output.xlsx";
        ExcelWriter excelWriter = EasyExcel.write(fileName, User.class).build();
        WriteSheet writeSheet = EasyExcel.writerSheet("Sheet1").build();

        int totalRows = 1000000; // 总数据量
        int batchSize = 10000; // 每个批次的数据量
        int threadCount = 10; // 线程数

        ExecutorService executor = Executors.newFixedThreadPool(threadCount);
        List<Future<List<User>>> futures = new ArrayList<>();

        // 分配任务给线程
        for (int i = 0; i < totalRows; i += batchSize) {
            int start = i;
            int end = Math.min(i + batchSize, totalRows);
            futures.add(executor.submit(() -> getBatchData(start, end)));
        }

        // 收集所有线程的结果
        for (Future<List<User>> future : futures) {
            List<User> batchData = future.get();
            excelWriter.write(batchData, writeSheet);
        }

        // 关闭资源
        excelWriter.finish();
        executor.shutdown();
    }

    // 模拟获取批次数据的方法
    private static List<User> getBatchData(int start, int end) {
        List<User> batchData = new ArrayList<>();
        for (int i = start; i < end; i++) {
            batchData.add(new User("Name" + i, i));
        }
        return batchData;
    }

    // 数据对象
    public static class User {
        private String name;
        private int age;

        public User(String name, int age) {
            this.name = name;
            this.age = age;
        }

        // getters and setters
    }
}